class SiteHeartBeat::Unavailable < SiteHeartBeat
  
  belongs_to :site_heart_beat_daily_stat, :counter_cache => :unavailable_site_heart_beats_count

  validates_presence_of :site_heart_beat_daily_stat_id

  def send_email!(options = {})
    if site_health_setting.allow_email?
      UserMailer.deliver_send_site_health_of_unavailable self,options if Rails.env != 'test'
      user.add_emails_count!
      site_health_setting.add_emails_count!
    end
  end

  def send_sm!
    if site_health_setting.allow_sms? and user.mobile?
      Sm.create!( :user => user,
        :content =>  "【#{site_heart_beat_daily_stat.site_health_setting.name}】#{I18n.l created_at, :format => :short}出现故障。今日的健康度是#{site_heart_beat_daily_stat.health_degree}%（#{site_heart_beat_daily_stat.available_site_heart_beats_count}次可用/#{site_heart_beat_daily_stat.unavailable_site_heart_beats_count}次故障），平均响应时间#{site_heart_beat_daily_stat.avg_response_time}ms#{ site_heart_beat_daily_stat.the_fastest_heart_beat ? "，最快响应时间#{site_heart_beat_daily_stat.the_fastest_heart_beat.try(:response_time)}ms，最慢响应时间#{site_heart_beat_daily_stat.the_slowest_heart_beat.try(:response_time)}ms" : ""}【麦吐司网】",
        :pri => 2) if Rails.env != 'test'
      user.add_sms_count!
      site_health_setting.add_sms_count!
    end
  end
  
  def before_save
  end

  def after_save
    site_heart_beat_daily_stat.reset_unavailables_stat!
    logger.debug "今日次数：#{site_heart_beat_daily_stat.available_site_heart_beats_count}"    
    logger.debug "今日失败次数：#{site_heart_beat_daily_stat.unavailable_site_heart_beats_count}"    
    if pre_one.nil? or pre_one.is_a?(SiteHeartBeat::Available)
      # send mails
      send_email
      send_sm
    end
  end

  def type_name
    '故障'
  end

end
